<?php

namespace Method;

/*
RSA2签名方法
*/
function RSA2sign($signatureContent)
{

    /*
商户私钥
*/
$private_key_str = 
"-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----";
    $private_key = openssl_pkey_get_private($private_key_str);
    openssl_sign($signatureContent, $signature, $private_key, OPENSSL_ALGO_SHA256);
    $sign = base64_encode($signature);
    //输出签名后数据
    return $sign;
}

//RSA2分段加密方法
function RSA2data($plaintext)
{
    /*
汇付宝公钥
*/
$partner_public_key_str = 
"-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----";
    $publicKey = openssl_pkey_get_public($partner_public_key_str);

// 获取公钥长度
$keyDetails = openssl_pkey_get_details($publicKey);
$keyLength = $keyDetails['bits'] / 8;

// 分段加密
$encryptedText = '';
$chunks = str_split($plaintext, $keyLength - 11); // 每段长度为密钥长度减去11
foreach ($chunks as $chunk) {
    $encryptedChunk = '';
    if (openssl_public_encrypt($chunk, $encryptedChunk, $publicKey)) {
        $encryptedText .= $encryptedChunk;
    } else {
        die('加密失败');
    }
}   
$encryptedText = base64_encode($encryptedText);
return $encryptedText;

}



function PostJson($Posturl,$jsonData)
{
// 目标URL
$url = $Posturl;


// 创建Header选项
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => $jsonData,
    ),
);

// 创建上下文选项
$context  = stream_context_create($options);

// 发送POST请求并获取响应

$response = file_get_contents($url, false, $context);

if ($response === false) {
    // 处理请求失败的情况
    echo "Failed to send POST request.";
} else {
    // 处理请求成功的响应
    return $response;
}
}

//私钥解密

function rsaDecrypt($encryptedData)
        {
            $private_key_str = 
"-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----";
            $res = openssl_pkey_get_private($private_key_str);
            $encrypted = '';
            $part_len = 256;
            $parts = str_split($encryptedData, $part_len);
            // dump($parts);
            foreach ($parts as $part) {
                $encrypted_temp = '';
                $result = openssl_private_decrypt($part, $encrypted_temp, $res);
                 if (!$result) {
                                die('Decryption failed: ' . openssl_error_string());
                            }
                $encrypted .= $encrypted_temp;
            }
        return $encrypted;
}
?>